<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医院名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入医院名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医院等级" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入医院等级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医院地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入医院地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['creditlife:hospital']"
        >查看挂号记录</el-button>
      </el-col>
      <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hospitalList" @selection-change="handleSelectionChange">
      <el-table-column label="医院序号" align="center" prop="hospitalId" />
      <el-table-column label="医院名字" align="center" prop="name" />
      <el-table-column label="医院等级" align="center" prop="level" />
      <el-table-column label="医院地址" align="center" prop="address" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button link type="primary" @click="handleAppointment(scope.row)" v-hasPermi="['creditlife:hospital']">预约挂号</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 医生列表对话框 -->
     <!-- 列表太小了，没办法显示完全 -->
    <!-- <el-dialog
      title="选择医生进行预约"
      :visible.sync="doctorDialogVisible"
      style="width: 60%;height: 600px; overflow: hidden;"
      append-to-body
    > -->
    <el-dialog
      title="选择医生进行预约"
      :visible.sync="doctorDialogVisible"
      width="80%"
      :style="{ height: '700px', overflow: 'auto' }"
      append-to-body
    >
      <el-input
        v-model="doctorSearch.name"
        placeholder="请输入医生名字搜索"
        clearable
        style="margin-bottom: 15px;"
        @keyup.enter.native="handleBookSearch"
      >
        <el-button slot="append" icon="el-icon-refresh" @click="resetBookSearch"></el-button>
      </el-input>
      <el-table
        :data="doctorList"
        border
        v-loading="doctorLoading"
        style="width: 100%"
      >
        <el-table-column
          prop="doctorId"
          label="医生序号"
          width="100"
        />
        <el-table-column
          prop="name"
          label="医生姓名"
        />
        <el-table-column
          prop="title"
          label="医生头衔"
          width="120"
        />
        <el-table-column
          prop="specialty"
          label="科室"
          width="140"
        />
        <el-table-column
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="handleViewSchedule(scope.row)"
            >
              挂号
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="doctorPageNum"
        :page-size="doctorPageSize"
        layout="total, prev, pager, next"
        :total="filteredDoctorTotal"
        style="margin-top: 20px; text-align: right;"
      />
    </el-dialog>

    <!-- 挂号记录对话框 -->
    <el-dialog
      title="挂号记录"
      :visible.sync="appointmentDialogVisible"
      style="width: 60%; height: 500px; overflow: hidden;"
      append-to-body
    >
      <div style="max-width: 1000px; margin: 0 auto;">
        <el-table
          :data="appointmentList"
          border
          v-loading="appointmentLoading"
          style="width: 100%; margin-bottom: 15px;"
          max-height="400"
        >
          <el-table-column
            prop="scheduleId"
            label="排班序号"
            min-width="80"
          />
          <el-table-column
            prop="doctorName"
            label="医生姓名"
            min-width="100"
          />
          <el-table-column
            prop="createTime"
            label="挂号时间"
            min-width="160"
          />
          <el-table-column
            label="操作"
            min-width="100"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleAppointmentDetail(scope.row)"
              >
                取消挂号
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @current-change="handleAppointmentCurrentChange"
          @size-change="handleAppointmentSizeChange"
          :current-page="appointmentPageNum"
          :page-size="appointmentPageSize"
          layout="total, sizes, prev, pager, next"
          :page-sizes="[5, 10, 20]"
          :total="appointmentTotal"
          style="text-align: right;"
        />
      </div>
    </el-dialog>

    <el-dialog
      title="医生出诊时间"
      :visible.sync="scheduleDialogVisible"
      style="width: 60%; height: 600px; overflow: hidden;"
      append-to-body
    >
      <el-table
        :data="scheduleList"
        border
        v-loading="scheduleLoading"
        style="width: 100%"
      >
        <el-table-column
          prop="scheduleId"
          label="排班序号"
          width="100"
        />
        <el-table-column
          prop="doctorName"
          label="医生姓名"
        />
        <el-table-column
          prop="date"
          label="出诊日期"
          width="120"
        />
        <el-table-column
          prop="available"
          label="可用号数"
          width="140"
        />
        <el-table-column
          label="操作"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="handleBookDoctor(scope.row)"
            >
              预约挂号
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listHospital, getDoctor, getDoctorSchedule, appointDoctor, getAppointmentList, cancelAppointment } from "@/api/creditlife/hospital"

export default {
  name: "Hospital",
  data() {
    return {
      // 挂号记录分页相关状态
      appointmentTotal: 0,
      appointmentPageNum: 1,
      appointmentPageSize: 10,
      // 挂号记录对话框相关状态
      appointmentDialogVisible: false,
      appointmentList: [],
      appointmentLoading: false,
      // 出诊时间对话框相关状态
      scheduleDialogVisible: false,
      scheduleList: [],
      scheduleLoading: false,
      selectedDoctorId: null,
      // 医院列表相关状态
      hospitalList: [],
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      // 医生列表相关状态
      doctorDialogVisible: false,
      doctorLoading: false,
      allDoctorList: [],
      filteredDoctorList: [],
      doctorList: [],
      filteredDoctorTotal: 0,
      doctorPageNum: 1,
      doctorPageSize: 10,
      doctorSearch: { name: '' },
      selectedHospitalId: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        level: null,
        address: null
      }
    }
  },
  created() {
    this.getList()
  },
  activated() {
    this.getList()
  },
  methods: {
    handleBookDoctor(row) {
      if (row.available <= 0) {
        this.$message.error("该医生当前没有可用号数");
        return;
      }
      const appointmentData = {
        scheduleId: row.scheduleId,
        doctorId: row.doctorId,
        doctorName: row.doctorName,
        appointmentDate: row.date,
        available: row.available
      }

      this.scheduleLoading = true;

      appointDoctor(appointmentData)
        .then(response => {
          this.scheduleLoading = false;
          if (response.code === 200) {
            this.$message.success("预约成功");
            this.scheduleDialogVisible = false;
          } else {
            this.$message.error("预约失败：" + response.msg);
          }
        });
    },
    handleAppointment(row) {
      this.selectedHospitalId = row.hospitalId;
      this.doctorPageNum = 1;
      this.doctorDialogVisible = true;
      this.doctorLoading = true;

      getDoctor(this.selectedHospitalId)
        .then(response => {
          this.doctorLoading = false;
          if (response.code === 200) {
            this.allDoctorList = response.data || [];
            this.handleBookSearch();
          } else {
            this.$message.error('获取医生列表失败：' + response.msg);
            this.allDoctorList = [];
            this.filteredDoctorList = [];
            this.doctorList = [];
            this.filteredDoctorTotal = 0;
          }
        })
        .catch(error => {
          this.doctorLoading = false;
          this.$message.error('请求医生列表出错：' + error.message);
        });
    },
    handleAppointmentDetail(row) {
      this.$confirm('确定要取消该挂号吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const cancelData = {
          appointmentId: row.appointmentId,
          userId: row.userId,
          scheduleId: row.scheduleId,
          doctorName: row.doctorName,
          status: row.status,
          createTime: row.createTime
        };
        this.appointmentLoading = true;

        cancelAppointment(cancelData)
          .then(response => {
            this.appointmentLoading = false;
            if (response.code === 200) {
              this.$message.success('取消挂号成功');
              this.handleAdd();
            } else {
              this.$message.error('取消挂号失败：' + response.msg);
            }
          })
          .catch(error => {
            this.appointmentLoading = false;
            this.$message.error('请求取消挂号失败：' + error.message);
          });
      }).catch(() => {
        this.$message.info('已取消取消挂号');
      });
    },
    handleViewSchedule(row) {
      this.selectedDoctorId = row.doctorId;
      this.scheduleLoading = true;

      getDoctorSchedule(row.doctorId)
        .then(response => {
          this.scheduleLoading = false;
          if (response.code === 200) {
            this.scheduleList = response.data || [];
            this.scheduleDialogVisible = true;
          } else {
            this.$message.error('获取出诊时间失败：' + response.msg);
          }
        })
        .catch(error => {
          this.scheduleLoading = false;
          this.$message.error('请求出诊时间出错：' + error.message);
        });
    },
    handleAdd() {
      this.appointmentLoading = true;
      getAppointmentList({
        pageNum: this.appointmentPageNum,
        pageSize: this.appointmentPageSize
      })
        .then(response => {
          this.appointmentLoading = false;
          if (response.code === 200) {
            this.appointmentList = response.data || [];
            this.appointmentTotal = response.data || 0;
            this.appointmentDialogVisible = true;
          } else {
            this.$message.error('获取挂号记录失败：' + response.msg);
          }
        });
    },
    handleAppointmentCurrentChange(newPage) {
      this.appointmentPageNum = newPage;
      this.handleAdd();
    },
    handleAppointmentSizeChange(newSize) {
      this.appointmentPageSize = newSize;
      this.appointmentPageNum = 1;
      this.handleAdd();
    },
    getList() {
      this.loading = true;
      listHospital(this.queryParams).then(response => {
        this.hospitalList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryRef.resetFields();
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.hospitalId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // handleBookSearch() {
    //   const keyword = this.doctorSearch.name.trim().toLowerCase();
    //
    //   this.filteredDoctorList = keyword
    //     ? this.allDoctorList.filter(doctor =>
    //       doctor.name.toLowerCase().includes(keyword)
    //     : [...this.allDoctorList];
    //
    //   this.filteredDoctorTotal = this.filteredDoctorList.length;
    //   this.updateCurrentPageData();
    // },
    handleBookSearch() {
      const keyword = this.doctorSearch.name.trim().toLowerCase();

      if (keyword) {
        this.filteredDoctorList = this.allDoctorList.filter(doctor => {
          return doctor.name.toLowerCase().includes(keyword);
        });
      } else {
        this.filteredDoctorList = [...this.allDoctorList];
      }

      this.filteredDoctorTotal = this.filteredDoctorList.length;
      this.updateCurrentPageData();
    },
    updateCurrentPageData() {
      const start = (this.doctorPageNum - 1) * this.doctorPageSize;
      const end = start + this.doctorPageSize;
      this.doctorList = this.filteredDoctorList.slice(start, end);
    },
    handleSizeChange(newSize) {
      this.doctorPageSize = newSize;
      this.updateCurrentPageData();
    },
    handleCurrentChange(newPage) {
      this.doctorPageNum = newPage;
      this.updateCurrentPageData();
    },
    resetBookSearch() {
      this.doctorSearch = { name: '' };
      this.doctorPageNum = 1;
      this.handleBookSearch();
    }
  }
}
</script>
